<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .right-text {
            text-align: right;
        }
        .left-text {
            text-align: left;
        }
    </style>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        let UserId="{{.UserId}}"
        let ws
        let userInfoListArray = new Array();

     //   window.onload = () => {
        function connect(){
            if ('WebSocket' in window) {
                // 创建websocket连接
                ws = new WebSocket( "ws://" + location.host + "/u/websocket/message?token={{.Token}}");
                // 成功连接的时候推送一条消息，此时服务端就可以开始推送数据了
                ws.onopen = () => {
                    console.log('websocket success---');
                    //下面是单聊,type=2
                    ws.send("{\"room_id\":\"20ad66931fe14cc2a2689e193ffff09c\",\"content\":\"gongcaihua\",\"type\":2,\"media\":1}");
                    //下面是群聊,type=1
                    //     ws.send("{\"to\":\"3c50e612ed1145a99e3e7166d8adcef0\",\"content\":\"gongcaihua\",\"type\":1,\"media\":1}");

                }
                ws.onmessage = (message) => {
                    let data = message.data;
                    console.log('data:', data);
                    var chatMessages = document.getElementById('chat-messages');
                    var msgData = JSON.parse(message.data);
                    if (typeof (userInfoListArray[msgData.userId]) != "undefined"){
                        chatMessages.innerHTML += '<p class=left-text>' + '<image src="' + userInfoListArray[msgData.userId].user_icon + '"  />' + userInfoListArray[msgData.userId].account + "说：" + msgData.content + '</p>';
                    }
                    else
                        chatMessages.innerHTML += '<p class=center-text>' + msgData.content + '</p>';
                    // chatMessages.innerHTML += '<p class=center-text>' + event.data + '</p>';
                    //  socket.send("{\"room_id\":\"58dc0b6ec3474835a947e12f89ac6fb2\",\"content\":\"gongcaihua\",\"type\":1}");
                }
                ws.onclose = function(e){
                    console.log("close,"+e.code);
                    console.log("开始重连，重连时间3秒");
                    setTimeout(connect, 3000); // 断开后尝试重连
                }



                ws.onerror = () => {
                    console.error('websocket fail');


                }
            } else {
                console.error('dont support websocket');
            };
        };
        function sendDemo(){

            ws.send(document.getElementById("messageInput").value);
            var chatMessages = document.getElementById('chat-messages');
            var msgData = JSON.parse(document.getElementById("messageInput").value);
            chatMessages.innerHTML += '<p class=right-text>'  + msgData.content + '</p>';

        }
        function clean(){
            var chatMessages = document.getElementById('chat-messages');
            chatMessages.innerHTML = '<p>清空</p>';

        }
        // 定义发送消息的函数
        function sendMessage() {
            // 这里可以是任何你想发送的数
            // 发送消息
            if (ws!=null) {
                ws.send(document.getElementById("messageInput").value);
                var chatMessages = document.getElementById('chat-messages');
                var msgData = JSON.parse(document.getElementById("messageInput").value);
                chatMessages.innerHTML += '<p class=right-text>'+ '<image src="' + userInfoListArray[UserId].user_icon + '"  />' + userInfoListArray[UserId].account+"说："+ msgData.content + '</p>';
            }
        }

        // 设置定时器，例如每5秒发送一次消息
        setInterval(sendMessage, 10000);


        var callback = function(data) {
            var chatMessages = document.getElementById('chat-messages');
            chatMessages.innerHTML = '<p>'+data+'</p>';
        //    result.innerHTML = data;
        }


        function clickUrl(url){
            getData(url, callback)
        }
         function getData(url, callback) {
            var xhr = new XMLHttpRequest();
            // 异步请求
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4) {
                    if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
                        callback && callback(xhr.responseText);
                    }
                }
            }


            xhr.open('GET', url, true);
            xhr.send();
        }
        function sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        async     function callbackChatList(data) {
           // alert(data)
            var chatMessages = document.getElementById('chat-messages');
            var chatList=JSON.parse(data).data.list
            chatMessages.innerHTML = '<p>用户数：'+chatList.length+'</p>';
            var value1=""
            for (let i = 0; i < chatList.length; i++) {
              //  console.log(chatList[i].user_id+"========="+userInfoListArray.length+JSON.stringify(userInfoListArray[chatList[i].user_id]))
                var chartdata=chatList[i].data
                if (chatList[i].user_id == UserId) {

                    value1 += '<p class=right-text>' + '<image src="' + userInfoListArray[chatList[i].user_id].user_icon + '"  />' + userInfoListArray[chatList[i].user_id].account + "说：" + chatList[i].content + '</p>';

                 }
                else
                    value1 += '<p class=left-text>' + '<image src="' + userInfoListArray[chatList[i].user_id].user_icon + '"  />' + userInfoListArray[chatList[i].user_id].account + "说：" + chatList[i].content + '</p>';



                //chatMessages.innerHTML = '<p>'+userInfoList[i].account+'</p>';
            }
             chatMessages.innerHTML += value1;
            //    result.innerHTML = data;
        }
   async      function callbackUserInfoList(data) {
            //   alert(data)
            var chatMessages = document.getElementById('user-list');
            var userInfoList=JSON.parse(data).data.list
            chatMessages.innerHTML = '<p>用户数：'+userInfoList.length+'</p>';
            var value1=""
            for (let i = 0; i < userInfoList.length; i++) {
                userInfoListArray[userInfoList[i].user_id]=userInfoList[i]
                value1 += '<image src="' + userInfoList[i].user_icon + '"  />' + userInfoList[i].account + '<br>';
                //console.log(userInfoListArray[userInfoList[i].UserId])
                if (i%1000==0) {
                    sleep(2).then(() => {
                        chatMessages.innerHTML += value1;
                        value1=""
                    });
                }

             //   chatMessages.innerHTML += value1;
            }

              chatMessages.innerHTML += value1;
        }
        function connectWebsocket(){
            connect()
            url="http://" + location.host + "/u/userRoom/findUserList?room_id=888888888888888888&token={{.Token}}"

            console.log(url)
            getData(url, callbackUserInfoList)





        }
        function chatList(){
            url="http://" + location.host + "/u/chat/list?page_size=10&page_index=1&room_id=888888888888888888&token={{.Token}}"
            getData(url, callbackChatList)
        }
        function prefixAccount(){
            url="http://" + location.host + "/u/userRoom/findUserList?prefixAccount=gongcaihua33&room_id=888888888888888888&&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVudGl0eSI6ImE1NzVmMTM5ZmQ0MDRjYjBiMjMyYTM2NTEwNjQ1NWMzIiwiZW1haWwiOiJnb25nY2FpaHVhMzg5In0.-IzbGzSnwx_aqlNMCEOjOy4_RjOoRMyWW7Jm5euKIgc"
            getData(url, callbackUserInfoList)
        }
    </script>

</head>
<body>

<button id="sendButton"  onclick="connectWebsocket()">建立连接</button>
UserId: {{.UserId}}
<br>

<input type="text" size="100" id="messageInput"  value='{"room_id":"888888888888888888","content":"gongcaihua","type":1,"media":1}'>
<button id="sendButton"  onclick="sendDemo()">发送</button>
<button id="sendButton"  onclick="clean()">清空</button>

<br>
<button id="sendButton"  onclick="clickUrl('./u/chat/list?page_size=10&page_index=1&room_id=888888888888888888&token={{.Token}}')">获得房间聊天内容</button>
<button id="sendButton"  onclick="chatList()">显示聊天内容</button>

<br>
<button id="sendButton"  onclick="clickUrl('./u/user/query?account=gongcaihua22&token={{.Token}}')">用户信息</button>

<br>
<button id="sendButton"  onclick="clickUrl('./u/user/findFriendsList?account=gongcaihua22&token={{.Token}}')">1对1聊天列表</button>
<button id="sendButton"  onclick="clickUrl('./u/userRoom/findUserList?room_id=888888888888888888&&token={{.Token}}')">房间内用户信息</button>
<a href="/u/userRoom/findUserList?prefixAccount=gongcaihua33&room_id=888888888888888888&&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVudGl0eSI6ImE1NzVmMTM5ZmQ0MDRjYjBiMjMyYTM2NTEwNjQ1NWMzIiwiZW1haWwiOiJnb25nY2FpaHVhMzg5In0.-IzbGzSnwx_aqlNMCEOjOy4_RjOoRMyWW7Jm5euKIgc"> 房间用户模糊查询</a>
<br>
<button id="sendButton"  onclick="clickUrl('./client')">登录用户数</button>

<button id="sendButton"  onclick="clickUrl('./insertManyRegister?size=100000')">插入用户数据</button>
<br>
<button id="sendButton"  onclick="clickUrl('./getReport?reportType=login:')">登录数/秒</button>
<br>
<button id="sendButton"  onclick="clickUrl('./getReport?reportType=send:')">消息/秒</button>
<br>
<button id="sendButton"  onclick="clickUrl('./sendToAllClient?content=gongceeeaihua22&token={{.Token}}')">群发消息</button>


<div style="display: flex;">
    <div  id="user-list" style="width: 30%; border:1px solid #000;overflow: auto; height:320px;">用户列表</div>
    <div id="chat-messages" style=" width:70%; border:1px solid #000;overflow: auto; height:320px;"></div>
</div>
</body>
</html>